<template>
  <el-dialog v-model="dialogVisible" title="添加题目" width="80%">
    <!-- 筛选表单 -->
    <el-form :inline="true" class="filter-form">
      <el-form-item label="题目ID">
        <el-input 
          v-model.number="filterForm.id" 
          placeholder="请输入题目ID" 
          clearable 
          style="width: 200px"
          @clear="onSubmit"
        />
      </el-form-item>
      
      <el-form-item label="题型">
        <el-select 
          v-model="filterForm.questionType" 
          style="width: 200px" 
          clearable 
          placeholder="请选择题型"
        >
          <el-option label="单选题" :value="1" />
          <el-option label="多选题" :value="2" />
          <el-option label="判断题" :value="3" />
          <el-option label="填空题" :value="4" />
          <el-option label="简答题" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 题目表格 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%"
      height="400"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55">
        <template #header>
          <el-checkbox v-model="isAllSelected" @change="handleSelectAll"></el-checkbox>
        </template>
      </el-table-column>
      
      <el-table-column prop="id" label="ID" width="80" align="center"/>
      
      <el-table-column label="题型" width="120" align="center">
        <template #default="{row}">
          {{ getQuestionTypeName(row.questionType) }}
        </template>
      </el-table-column>
      
      <el-table-column label="题干" min-width="300">
        <template #default="{row}">
          <div class="question-title">{{ row.shortTitle }}</div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div style="margin-top: 20px; display: flex; justify-content: center;">
      <el-pagination 
        background 
        layout="prev, pager, next, sizes, total" 
        :total="total" 
        :page-size="filterForm.pageSize"
        :current-page="filterForm.pageIndex"
        :page-sizes="[5, 10, 20, 50]"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave">添加选中题目</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getQuestionPage, getSubjectList } from '@/api/juanti';
import type { Subject, QuestionItem } from '@/api/juanti';

// 筛选表单（包含分页参数）
const filterForm = reactive({
  id: null as number | null,
  questionType: null as number | null,
  level: null as number | null,
  subjectId: null as number | null,
  pageIndex: 1,
  pageSize: 10
});

// 题目表格数据
const tableData = ref<QuestionItem[]>([]);
const total = ref(0);
const loading = ref(false);

// 学科列表
const subjectList = ref<Subject[]>([]);

// 存储选中的行
const selectedRows = ref<QuestionItem[]>([]);
// 全选状态
const isAllSelected = ref(false);

// 控制对话框的显示与隐藏
const dialogVisible = ref(false);

// 定义可以触发的事件
const emit = defineEmits(['addQuestions']);

// 题型映射
const questionTypes = [
  { id: 1, name: '单选题' },
  { id: 2, name: '多选题' },
  { id: 3, name: '判断题' },
  { id: 4, name: '填空题' },
  { id: 5, name: '简答题' }
];

// 根据题型ID获取题型名称
const getQuestionTypeName = (typeId: number): string => {
  const type = questionTypes.find(t => t.id === typeId);
  return type ? type.name : `题型${typeId}`;
};

// 格式化日期
const formatDate = (dateString: string): string => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 获取题目列表
const getQuestionList = async () => {
  try {
    loading.value = true;
    const params = {
      id: filterForm.id,
      questionType: filterForm.questionType,
      level: filterForm.level,
      subjectId: filterForm.subjectId,
      pageIndex: filterForm.pageIndex,
      pageSize: filterForm.pageSize
    };
    
    const res = await getQuestionPage(params);
    
    // 安全访问响应数据
    if (res && res.code === 1 && res.response) {
      tableData.value = res.response.list || [];
      total.value = res.response.total || 0;
    } else {
      const errorMsg = res?.message || '获取题目列表失败';
      ElMessage.error(errorMsg);
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取题目列表出错:', error);
    ElMessage.error('获取题目列表出错');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
    // 重置全选状态
    isAllSelected.value = false;
    selectedRows.value = [];
  }
};

// 获取学科列表
const fetchSubjectList = async () => {
  try {
    const res = await getSubjectList();
    
    // 确保响应有效
    if (res && res.code === 1 && Array.isArray(res.response)) {
      subjectList.value = res.response;
    } else {
      const errorMsg = res?.message || '获取学科列表失败';
      console.error(errorMsg);
      ElMessage.error(errorMsg);
      subjectList.value = [];
    }
  } catch (error) {
    console.error('获取学科列表出错:', error);
    ElMessage.error('获取学科列表出错');
    subjectList.value = [];
  }
};

// 查询
const onSubmit = () => {
  filterForm.pageIndex = 1; // 重置为第一页
  getQuestionList();
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.id = null;
  filterForm.questionType = null;
  filterForm.level = null;
  filterForm.subjectId = null;
  filterForm.pageIndex = 1;
  getQuestionList();
};

// 分页处理 - 页码变化
const handleCurrentChange = (val: number) => {
  filterForm.pageIndex = val; // 更新当前页码
  getQuestionList();
};

// 分页处理 - 每页数量变化
const handleSizeChange = (val: number) => {
  filterForm.pageSize = val;
  filterForm.pageIndex = 1; // 重置为第一页
  getQuestionList();
};

// 提供一个方法用于打开对话框
const openDialog = () => {
  // 重置筛选条件
  resetFilter();
  // 清空选中项
  selectedRows.value = [];
  isAllSelected.value = false;
  
  dialogVisible.value = true;
};

// 处理行选择变化
const handleSelectionChange = (val: QuestionItem[]) => {
  selectedRows.value = val;
  isAllSelected.value = val.length === tableData.value.length;
};

// 处理全选
const handleSelectAll = (val: boolean) => {
  if (val) {
    selectedRows.value = [...tableData.value];
  } else {
    selectedRows.value = [];
  }
  isAllSelected.value = val;
};

// 保存按钮点击事件处理函数
const handleSave = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个题目');
    return;
  }
  
  // 触发添加题目事件
  emit('addQuestions', selectedRows.value);
  
  // 显示成功消息
  ElMessage.success(`成功添加 ${selectedRows.value.length} 个题目`);
  
  // 关闭对话框
  dialogVisible.value = false;
};

// 取消按钮点击事件处理函数
const handleCancel = () => {
  // 清空选中的数据
  selectedRows.value = [];
  // 关闭对话框
  dialogVisible.value = false;
};

// 组件挂载时获取学科列表
onMounted(() => {
  fetchSubjectList();
});

defineExpose({
  openDialog
});
</script>

<style scoped>
.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 15px;
}

.filter-form .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

.el-table {
  margin-top: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.question-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 激活页码的样式 */
:deep(.el-pagination.is-background .el-pager li.active) {
  background-color: #409eff;
  color: #fff;
}

/* 鼠标悬停在页码上的样式 */
:deep(.el-pagination.is-background .el-pager li:not(.disabled):hover) {
  color: #409eff;
}
</style>